
function dealFlowPrimaryChange(data1){
let maxDrawdown = 0;
let maxStartIndex = -1;
let maxEndIndex = -1;
let inDrawdown = false;
let currentStart = -1;
let currentPeak = null;
for (let i = 1; i < data1.length; i++) {
    const prev = data1[i - 1];
    const current = data1[i];
    
    if (current < prev) {
        if (!inDrawdown) {
            // 开始新的下跌趋势
            inDrawdown = true;
            currentPeak = prev;  // 记录峰值
            currentStart = i - 1; // 记录起始索引
            const drawdown = currentPeak - current;
            
            if (drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
                maxStartIndex = currentStart;
                maxEndIndex = i;
            }
        } else {
            // 延续下跌趋势
            const drawdown = currentPeak - current;
            
            // 只有当出现更大跌幅时才更新结束位置
            if (drawdown > maxDrawdown) {
                maxDrawdown = drawdown;
                maxStartIndex = currentStart;
                maxEndIndex = i;
            }
        }
    } else {
        // 结束下跌趋势
        inDrawdown = false;
    }
}

return {
  flow_num:maxDrawdown.toFixed(2),
  startdx:maxStartIndex,
  endIdx:maxEndIndex
}
} 

//处理生成当前区间
function dealDescription(num,inflow,time,period,data_type){
  const start = num.length - period;
  let values = num.slice(start).map(Number);
  let flows = inflow.slice(start).map(Number);
  let times = time.slice(start);
  let secondaryIdx_end=0;
  if(data_type==0){
    flows=inflow;
    times=time;
    values=num;
  }
  if(data_type==3){
 
    values = num.slice(0,start).map(Number);
     flows = inflow.slice(0,start).map(Number);
     times = time.slice(0,start);
  }
  const timeAt = idx => times[idx];
  let maxIdx = values.indexOf(Math.max(...values));
  let minIdx = values.indexOf(Math.min(...values));
  let secondaryIdx, change, duration, description,primaryChange;

  //开始时间和结束时间
  let start_time,end_time,sz_start_time,sz_end_time;
  if (maxIdx > minIdx) {
    // After max, find worst drop
    const segment = flows.slice(maxIdx);
    const segMin = Math.min(...segment);
    secondaryIdx = flows.indexOf(segMin, maxIdx);
    change = flows[secondaryIdx] - flows[maxIdx];
    duration = secondaryIdx - maxIdx;
    description = `${timeAt(maxIdx)} 到 ${timeAt(secondaryIdx)}`;
    secondaryIdx_end=secondaryIdx
    primaryChange = flows[maxIdx] - flows[minIdx];
    end_time=secondaryIdx
    start_time=maxIdx
    if(change==0){
       const dealChange=dealFlowPrimaryChange(flows);
       change=-parseFloat(dealChange.flow_num);
       description= `${timeAt(dealChange.startdx)} 到 ${timeAt(dealChange.endIdx)}`;
       secondaryIdx_end=dealChange.endIdx
       duration=dealChange.endIdx-dealChange.startdx;
       end_time=dealChange.endIdx
       start_time=dealChange.startdx
    }
  } else {
    const segment = flows.slice(0, minIdx);
    const segMax = Math.max(...segment);
    secondaryIdx = flows.indexOf(segMax);
    change = flows[minIdx] - flows[secondaryIdx];
    duration = minIdx - secondaryIdx;
    description = `${timeAt(secondaryIdx)} 到 ${timeAt(minIdx)}`;
   secondaryIdx_end=minIdx

    const  s_segment=flows.slice(0,maxIdx);
    const  s_segMin = Math.min(...s_segment);
    let  end_segment_flow=flows.slice(minIdx, flows.length);
    let  end_segment=Math.max(...end_segment_flow);
    if( flows[maxIdx]-s_segMin>end_segment-flows[minIdx] ){
      primaryChange=flows[maxIdx]-s_segMin;
      minIdx= flows.indexOf(s_segMin);
    }else{
      primaryChange=end_segment-flows[minIdx];
      maxIdx=minIdx+end_segment_flow.indexOf(end_segment);
    }
    if(maxIdx-minIdx==0){
      const get_interval=getInterval(flows);
      minIdx=get_interval.start;
      maxIdx=get_interval.end;
      primaryChange=get_interval.increase;
   }
    end_time=minIdx
    start_time=secondaryIdx
  }
 
 let sz_description=`${timeAt(minIdx)} 到 ${timeAt(maxIdx)}`;
 let sz_duration=maxIdx-minIdx;
 sz_end_time=minIdx
 return {
  primaryChange,
  sz_description,
  sz_duration,
  sz_end_time,
  maxIdx:timeAt(maxIdx),
  minIdx:timeAt(minIdx),
  change,
  description,
  start_time:timeAt(secondaryIdx),
  end_time:timeAt(secondaryIdx_end),
  duration,
 
 }
}
//获取区间
function getInterval(data){
  const { start, end, increase } = data.reduce(({ start, end, increase, currentStart, currentIncrease }, curr, i) => {
    if (i === 0) return { start, end, increase, currentStart, currentIncrease }; // 跳过第一个元素
    
    const prev = data[i - 1];
    const isRising = curr > prev;
    
    currentStart = isRising ? (currentStart === -1 ? i - 1 : currentStart) : -1;
    currentIncrease = isRising ? (currentStart === i - 1 ? curr - prev : currentIncrease + curr - prev) : 0;
    
    return currentIncrease > increase 
      ? { start: currentStart, end: i, increase: currentIncrease, currentStart, currentIncrease } 
      : { start, end, increase, currentStart, currentIncrease };
  }, { start: -1, end: -1, increase: 0, currentStart: -1, currentIncrease: 0 });

  return { start, end, increase };
}
//处理全部返回数据
function dealAllData(this_dd,period){
  return  [    {
    name: `近${period}日上涨`,  
    num: parseFloat(this_dd.primaryChange).toFixed(2),
    time:this_dd.sz_description,
    index:this_dd.sz_duration,
    end_time:this_dd.maxIdx,
    start_time:this_dd.minIdx
  },
  {
    name: `近${period}日下跌`,  
    num: parseFloat(this_dd.change).toFixed(2),
    time: this_dd.description,
    index:this_dd.duration+1,
    end_time:this_dd.end_time,
    start_time:this_dd.start_time
  }]
}
//data_type 数据类型 2=过多的重复循环，1=只有一个
export function dealFlowData({ num, inflow, time }, period,data_type) {
  
  num=num.map(Number);
 
  // Ensure sufficient data
  if (num.length < period) return null;
  const start = num.length - period;
  let flows = inflow.slice(start).map(Number);
  let times = time.slice(start);
  if(data_type==0){
    flows=inflow;
    times=time;
  }
  const timeAt = idx => times[idx];
  let this_dd=dealDescription(num,inflow,time,period,data_type);
  let this_dd_2=null;
  let this_dd_3=null;
  //全部的数据
  let all_data=null;
  if(data_type!=2){
  //上一个10天的数据

     this_dd_2=dealDescription(num.slice(0,start),inflow.slice(0,start),time.slice(0,start),period,data_type);
     this_dd_2=dealAllData(this_dd_2,period);
     this_dd_3=dealDescription(num.slice(0,start-period),inflow.slice(0,start-period),time.slice(0,start-period),
     period,data_type);
     this_dd_3=dealAllData(this_dd_3,period);
     all_data=[...this_dd_2,...this_dd_3]
  }
  let one_data=dealAllData(this_dd,period)
  let two_data=one_data[1];
  one_data=one_data[0];
  if(all_data!=null){
    two_data.item_data=[two_data,all_data[1],all_data[3]]
    one_data.item_data=[one_data,all_data[0],all_data[2]]
  }
  return [
    one_data,
    two_data,
    {
      name: `40日最小值到现在`,  
      num: (flows[flows.length - 1] - flows[this_dd.sz_end_time]).toFixed(2),
      time: `${this_dd.minIdx} 到 ${timeAt(flows.length - 1)}`,
      index:period - this_dd.sz_end_time - 1,
      end_time:timeAt(flows.length - 1),
    },
  ];
}  
//处理找到里面的最大的
export function cycleMax(day_list_data){
// 辅助函数：比较两条记录
  const compareRecords = (a, b, isLatest, isMax) => {
    const timeA = new Date(a.end_time);
    const timeB = new Date(b.end_time);
    const timeComp = isLatest ? timeA - timeB : timeB - timeA;
    
    return timeComp !== 0 
      ? timeComp > 0 ? a : b 
      : (isMax ? a.num - b.num : b.num - a.num) > 0 ? a : b;
  };

  // 查找关键记录
  const latestMax = day_list_data.reduce((prev, curr) => compareRecords(prev, curr, true, true));
  const latestMin = day_list_data.reduce((prev, curr) => compareRecords(prev, curr, true, false));
  const globalMax = day_list_data.reduce((prev, curr) => curr.num > prev.num ? curr : prev);
  const globalMin = day_list_data.reduce((prev, curr) => curr.num < prev.num ? curr : prev);

  // 标记并返回结果
  const result = day_list_data.map(item => {
    const active = [
      item === latestMax ? 1 : null,
      item === latestMin ? 2 : null,
      item === globalMax ? 3 : null,
      item === globalMin ? 4 : null
    ].filter(Boolean);
    
    return active.length ? {...item, active} : item;
  });
  return result

}

export function getYearlyFluctuation({ num, inflow, time }){
  // 用于存储结果的对象
  const result = {};
  // 遍历日期数组
  time.forEach((dateStr, index) => {
      // 提取年份
      const year = dateStr.split('-')[0];
      // 如果该年份还没有对应的数组，则初始化
      if (!result[year]) {
          result[year] = {
              dates: [],
              start: index,
              end: index
          };
      }
      // 添加日期到对应年份的数组
      result[year].dates.push(dateStr);
      // 更新结束位置
      result[year].end = index;
  });
  // 转换结果为数组格式
  const groupedResult = Object.entries(result).map(([year, data]) => ({
      year,
      dates: data.dates,
      start: data.start,
      end: data.end,
      num:num.slice(data.start, data.end + 1),
      inflow:inflow.slice(data.start, data.end + 1),
      time:time.slice(data.start, data.end + 1)
  }));
  let gr_array=[]
  let gr_array_2=[]
  groupedResult.forEach(item=>{
     let data1= dealDescription(item.num,item.inflow,item.time,0,3)
     data1=dealAllData(data1,item.year)
     gr_array.push(data1[0])
     gr_array_2.push(data1[1])
  })
  return {
    sz:gr_array.reverse(),
    xd:gr_array_2.reverse()
  }
}
export default { dealFlowData,cycleMax,getYearlyFluctuation };
